﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;
using System.IO;

namespace LED_Tester
{
    public partial class frmL6 : Form
    {
        public frmL6()
        {
            InitializeComponent();
        }

        #region 电源变量

        private ClassSourceMeter classSourceMeter;
        private int sourceMode;
        private SerialPort sptSource;
        private bool sourceIsJoin;
        private double voltSet;
        private double currSet;
        private double voltCheck;
        private double currCheck;

        public ClassSourceMeter Class_SourceMeter
        {
            get { return classSourceMeter; }
            set { classSourceMeter = value; }
        }
        public int SourceMode
        {
            get { return sourceMode; }
            set { sourceMode = value; }
        }
        public SerialPort SPTSource
        {
            get { return sptSource; }
            set { sptSource = value; }
        }
        public bool SourceIsJoin
        {
            get { return sourceIsJoin; }
            set { sourceIsJoin = value; }
        }
        public double VoltSet
        {
            get { return voltSet; }
            set { voltSet = value; }
        }
        public double CurrSet
        {
            get { return currSet; }
            set { currSet = value; }
        }

        #endregion

        #region 光强板变量

        private ClassLuxBoard classLuxBoard;
        private bool luxIsJoin;
        private double distance;
        private double luxStanValue;
        private double luxDarkValue;

        public ClassLuxBoard Class_LuxBoard
        {
            get { return classLuxBoard; }
            set { classLuxBoard = value; }
        }
        public bool LuxIsJoin
        {
            get { return luxIsJoin; }
            set { luxIsJoin = value; }
        }
        public double Distance
        {
            get { return distance; }
            set { distance = value; }
        }
        public double LuxDarkValue
        {
            get { return luxDarkValue; }
            set { luxDarkValue = value; }
        }

        #endregion

        #region 光谱仪变量

        private ClassSpectralMeter classSpectralMeter;
        private bool spectralIsJoin;
        private ClassSpectralMeter.Param param;
        private ClassSpectralMeter.Result result;

        public ClassSpectralMeter Class_SpectralMeter
        {
            get { return classSpectralMeter; }
            set { classSpectralMeter = value; }
        }
        public bool SpectralIsJoin
        {
            get { return spectralIsJoin; }
            set { spectralIsJoin = value; }
        }

        public ClassSpectralMeter.Param Param
        {
            get { return param; }
            set { param = value; }
        }
        public ClassSpectralMeter.Result Result
        {
            get { return result; }
            set { result = value; }
        }

        #endregion

        #region 其它变量

        private int index;
        private int timeSpace;
        private bool isMeasure = false;
        private bool isL6 = true;
        private double luxParam;
        private string[] information;
        private bool isR6 = true;

        private Thread threadMeasure;
        private ClassAppConfigure classAppConfigure;


        private delegate void dlgShowButton();
        private delegate void dlgDisplay();

        public int TimeSpace
        {
            get { return timeSpace; }
            set { timeSpace = value; }
        }
        public double LuxParam
        {
            get { return luxParam; }
            set { luxParam = value; }
        }
        public string[] Information
        {
            get { return information; }
            set { information = value; }
        }

        #endregion

        #region 功能函数

        private void enableButton()
        {
            tlClear.Enabled = true;
            tlSave.Enabled = true;
            tlSetting.Enabled = true;
            tlMeasure.Enabled = true;
        }

        private void unableButton()
        {
            tlClear.Enabled = false;
            tlSave.Enabled = false;
            tlSetting.Enabled = false;
            tlMeasure.Enabled = false;
        }

        private void loadConfig()
        {
            classAppConfigure = new ClassAppConfigure(Application.StartupPath + "\\data.ini.xml");
            timeSpace = classAppConfigure.TimeSpace;
        }

        private void saveConfig()
        {
            classAppConfigure.TimeSpace = timeSpace;
            classAppConfigure.Save();
        }

        private void output()
        {
            //int[] dataCount = new int[dgvList.ColumnCount - 1];

            //for (int i = 0; i < dataCount.Length; i++)
            //{
            //    dataCount[i] = 1;
            //}

            //SaveFileDialog sfdOutput = new SaveFileDialog();

            //sfdOutput.Filter = "files (*.xls)|*.xls";
            //sfdOutput.FilterIndex = 0;
            //sfdOutput.Title = "保存为Excel文件";
            //sfdOutput.FileName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00"); //默认保存文件名
            //if (sfdOutput.ShowDialog() == DialogResult.OK)
            //{
            //    ClassExportExcel classExportExcel = new ClassExportExcel();
            //    classExportExcel.StartThread(dgvList, information, dataCount, sfdOutput.FileName);
            //}

            SaveFileDialog sfdOutput = new SaveFileDialog();

            sfdOutput.Filter = "CSV (逗号分隔)(*.csv)|*.csv";
            sfdOutput.FilterIndex = 0;
            sfdOutput.Title = "另存为";
            sfdOutput.FileName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00"); //默认保存文件名

            if (sfdOutput.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter sw = new StreamWriter(sfdOutput.FileName, false, Encoding.Default))
                {
                    StringBuilder sb = new StringBuilder();
                    //sb.Append("产品类型：").Append(",").Append(information[0]).Append("\r\n");
                    //sb.Append("厂    商：").Append(",").Append(information[1]).Append("\r\n");
                    //sb.Append("日    期：").Append(",").Append(information[2]).Append("\r\n");
                    //sb.Append("环境温度：").Append(",").Append(information[3]).Append("\r\n");
                    //sb.Append("环境湿度：").Append(",").Append(information[4]).Append("\r\n");
                    //sb.Append("测试人员：").Append(",").Append(information[5]).Append("\r\n").Append("\r\n");

                    for (int i = 0; i < dgvList.Columns.Count; i++)
                    {
                        if (i == dgvList.Columns.Count)
                        {
                            sb.Append(dgvList.Columns[i].HeaderText).Append("\r\n");
                        }
                        else
                        {
                            sb.Append(dgvList.Columns[i].HeaderText).Append(",");
                        }
                    }

                    for (int i = 0; i < dgvList.Rows.Count; i++)
                    {
                        for (int j = 0; j < dgvList.Columns.Count - 1; j++)
                        {
                            if (j == dgvList.Columns.Count)
                            {
                                sb.Append(dgvList[j, i].Value.ToString()).Append("\r\n");
                            }
                            else
                            {
                                sb.Append(dgvList[j, i].Value.ToString()).Append(",");
                            }
                        }
                    }

                    sw.WriteLine(sb.ToString());
                    sw.Close();
                }
            }
        }

        private void measure()
        {
            if (isMeasure)
            {
                do
                {
                    classSourceMeter.LightOn(sourceMode, sptSource);
                    classSpectralMeter.MeasureCandela(param, ref luxStanValue);
                    Thread.Sleep(300);
                    classSourceMeter.Measure(sourceMode, sptSource, ref voltCheck, ref currCheck);
                    classSourceMeter.LightOff(sourceMode, sptSource);
                    BeginInvoke(new dlgDisplay(display));
                    Thread.Sleep(timeSpace);
                }
                while (true);
            }
        }

        private void display()
        {
            luxStanValue *= luxParam;

            chartLux.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].X.Add(currCheck);
            chartLux.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].Y.Add(luxStanValue);

            DataGridViewRow row = new DataGridViewRow();
            row.CreateCells(dgvList);

            row.Cells[0].Value = index.ToString("#00");
            row.Cells[1].Value = luxStanValue.ToString();
            row.Cells[2].Value = (index * timeSpace).ToString();

            dgvList.Rows.Add(row);

            index++;
        }

        private void clear()
        {
            index = 1;

            chartLux.ChartGroups.ChartGroupsCollection[0].ChartData.SeriesList[0].PointData.Clear();

            dgvList.Rows.Clear();
        }

        #endregion

        #region 按钮事件

        private void tlSave_Click(object sender, EventArgs e)
        {
            if (dgvList.Rows.Count == 0)
            {
                return;
            }
            else
            {
                output();
            }
        }

        private void tlClear_Click(object sender, EventArgs e)
        {
            clear();
        }

        private void tlSetting_Click(object sender, EventArgs e)
        {
            frmRMeasSetting frm_RMeasSeting = new frmRMeasSetting();

            frm_RMeasSeting.Param = param;
            frm_RMeasSeting.TimeSpace = timeSpace;
            frm_RMeasSeting.VoltSet = voltSet;
            frm_RMeasSeting.CurrMax = currSet;
            frm_RMeasSeting.IsR6 = isR6;

            frm_RMeasSeting.ShowDialog();

            if (frm_RMeasSeting.DialogResult == DialogResult.OK)
            {
                param = frm_RMeasSeting.Param;
                timeSpace = frm_RMeasSeting.TimeSpace;
                voltSet = frm_RMeasSeting.VoltSet;
                currSet = frm_RMeasSeting.CurrMax;
            }
        }

        private void tlMeasure_Click(object sender, EventArgs e)
        {
            if (!sourceIsJoin)
            {
                MessageBox.Show("电源未连接！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (!luxIsJoin)
            {
                MessageBox.Show("光强板未连接！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            clear();

            threadMeasure = new Thread(measure);
            isMeasure = true;
            unableButton();
            threadMeasure.Start();
        }

        private void tlStop_Click(object sender, EventArgs e)
        {
            if (isMeasure)
            {
                classSourceMeter.LightOff(sourceMode, sptSource);

                if (threadMeasure != null)
                {
                    if (threadMeasure.IsAlive)
                    {
                        threadMeasure.Abort();
                    }
                }

                BeginInvoke(new dlgShowButton(enableButton));

                isMeasure = false;

                MessageBox.Show("暂停测试！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("未进行测量！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        #endregion

        #region 窗体事件

        private void frmL6_Load(object sender, EventArgs e)
        {
            loadConfig();

            if (!sourceIsJoin)
            {
                MessageBox.Show("电源未连接！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            if (!spectralIsJoin)
            {
                MessageBox.Show("光谱仪未连接！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            clear();
        }

        private void frmL6_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isMeasure)
            {
                MessageBox.Show("正在测试！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (sourceIsJoin)
                {
                    classSourceMeter.LightOff(sourceMode, sptSource);
                }

                if (threadMeasure != null)
                {
                    if (threadMeasure.IsAlive)
                    {
                        threadMeasure.Abort();
                    }
                }

                saveConfig();
            }
        }

        #endregion
    }
}
